package com.h3bpm.web.msg.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 自定义http类
 *
 */
public class HttpLocalUtils {

    public static String doPost(String url, Map<String, Object> map, String contentType, String authorization) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        HttpMethodParams params = postMethod.getParams();
        params.setContentCharset("UTF-8");

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        if (contentType == null || "".equals(contentType)) {
            postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        } else {
            postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        if (authorization == null || "".equals(authorization)) {
        } else {
            postMethod.addRequestHeader("Authorization", authorization);
        }
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();
        // 循环遍历，获取迭代器
        Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> mapEntry = iterator.next();
            postMethod.addParameter(mapEntry.getKey(), mapEntry.getValue().toString());
        }

        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200) {
                res = postMethod.getResponseBodyAsString();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static String sendHttpPost(String url, String jsonBody, String authorization) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.addHeader("Authorization", authorization);
            httpPost.setEntity(new StringEntity(jsonBody));
            CloseableHttpResponse response = null;

            response = httpClient.execute(httpPost);

            //  System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            //  System.out.println(responseContent);
            response.close();
            httpClient.close();

            return responseContent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 以post方式调用第三方接口
     *
     * @param url
     * @param json
     * @return
     */
    private static CloseableHttpClient httpClient = null;

    //private static String tokenString = "Bearer B537F8B88ABE48EF958DFB0E4DD28E89";
    public static String doPost2(String url, String json, String authorization) {

        try {
            httpClient = HttpClientBuilder.create().build();
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
                    .setSocketTimeout(2000).setConnectTimeout(2000).build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            post.addHeader("Content-Type", "application/json;charset=utf-8");
            post.addHeader("Authorization", authorization);
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * HTTP发送post、put请求，带header、body的方法，获取结果
     *
     * @param url
     * @param requestMethod POST、PUT
     * @param
     * @param
     * @return
     * @author yswKnight
     */
    public static String httpRequest(String url, String requestMethod, String authorization, String params) {
        String result = "";
        HttpURLConnection connection = null;
        BufferedReader in = null;
        OutputStreamWriter outer = null;
        InputStream ips = null;
        StringBuffer buffer = null;

        try {
            URL restURL = new URL(url);
            connection = (HttpURLConnection) restURL.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //循环增加header

            connection.setRequestProperty("Authorization", authorization);


            outer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            //outer.write(params);
            outer.flush();
            outer.close();

            connection.connect();
            ips = connection.getInputStream();
            System.out.println("new String(ips) = " + ips.toString());

            in = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
            buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
                buffer.append("\r\n");
            }
            in.close();
            ips.close();
            //得到结果
            result = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
        return result;
    }

    private static String httpURLPOSTCase(String methodUrl, String body, String Authorization) {
        HttpURLConnection connection = null;
        OutputStream dataout = null;
        BufferedReader reader = null;
        String line = null;
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
            connection.setDoOutput(true);// 设置是否向connection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true,默认情况下是false
            connection.setDoInput(true); // 设置是否从connection读入，默认情况下是true;
            connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
            connection.setUseCaches(false);// post请求不能使用缓存设为false
            connection.setConnectTimeout(3000);// 连接主机的超时时间
            connection.setReadTimeout(3000);// 从主机读取数据的超时时间
            connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
            connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
            connection.setRequestProperty("charset", "utf-8");

            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", Authorization);
            connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要

            dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
            dataout.write(body.getBytes());
            dataout.flush();
            dataout.close();
            System.out.println(connection.getResponseCode());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
                StringBuilder result = new StringBuilder();
                // 循环读取流
                while ((line = reader.readLine()) != null) {
                    result.append(line).append(System.getProperty("line.separator"));//
                }
                System.out.println(result.toString());
                return String.valueOf(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
           /* try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();*/
        }
        return null;
    }

    /**
     * 发送GET请求
     *
     * @param url
     *            目的地址
     * @param parameters
     *            请求参数，Map类型。
     * @return 远程响应结果
     */
    public static String sendGet2(String url, Map<String, String> parameters) {
        String result="";
        BufferedReader in = null;// 读取响应输入流
        StringBuffer sb = new StringBuffer();// 存储参数
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数
            if(parameters.size()==1){
                for(String name:parameters.keySet()){
                    sb.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),
                                    "UTF-8"));
                }
                params=sb.toString();
            }else{
                for (String name : parameters.keySet()) {
                    sb.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),
                                    "UTF-8")).append("&");
                }
                String temp_params = sb.toString();
                params = temp_params.substring(0, temp_params.length() - 1);
            }
            String full_url = url + "?" + params;
            System.out.println(full_url);
            // 创建URL对象
            URL connURL = new URL(full_url);
            // 打开URL连接
            HttpURLConnection httpConn = (HttpURLConnection) connURL
                    .openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            // 建立实际的连接
            httpConn.connect();
            // 响应头部获取
            Map<String, List<String>> headers = httpConn.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : headers.keySet()) {
                System.out.println(key + "\t：\t" + headers.get(key));
            }
            // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn
                    .getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result ;
    }

    /**
     * 发送POST请求
     *
     * @param url
     *            目的地址
     * @param parameters
     *            请求参数，Map类型。
     * @return 远程响应结果
     */
    public static String sendPost2(String url, Map<String, String> parameters) {
        String result = "";// 返回的结果
        BufferedReader in = null;// 读取响应输入流
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();// 处理请求参数
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数
            if (parameters.size() == 1) {
                for (String name : parameters.keySet()) {
                    sb.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),
                                    "UTF-8"));
                }
                params = sb.toString();
            } else {
                for (String name : parameters.keySet()) {
                    sb.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),
                                    "UTF-8")).append("&");
                }
                String temp_params = sb.toString();
                params = temp_params.substring(0, temp_params.length() - 1);
            }
            // 创建URL对象
            URL connURL = new URL(url);
            // 打开URL连接
            HttpURLConnection httpConn = (HttpURLConnection) connURL
                    .openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            // 设置POST方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn
                    .getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 主函数，测试请求
     *
     * @param args
     */
    /*public static void main(String[] args) {
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("userName", "姜倩");
        parameters.put("jobNo", "H04-21246");
        String result =sendGet2("http://120.25.219.66:8082/Portal/OaUnitUser/getUser", parameters);
        System.out.println(result);
    }*/

   /* public static void main(String[] args) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = dateFormat.format(now);
        MD5 md5 = new MD5();
        String SecretKey = md5.getMD5ofStr(122757 + 298041 + timeStamp);
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("Methods","SmsSend");
        map.put("CorpID","122757");
        map.put("LoginName","Admin");
        //map.put("Password","298041");
        map.put("SecretKey",SecretKey);
        map.put("TimeStamp",timeStamp);
        map.put("PhoneNumbers","15257591018");
        map.put("LongSms","0");
        map.put("Content","测试");
        String s = sendGet2("http://sms.mobset.com:8095/SDK3/Sms", map);
        System.out.println(s);
    }*/
    //   public static void main(String[] args) {
    //    Date now = new Date();
    //    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    //    String timeStamp = dateFormat.format(now);
    //    MD5 md5 = new MD5();
    //    String SecretKey = md5.getMD5ofStr(129703 + "Tjec298041" + timeStamp);//129703
    //    LinkedHashMap<String, String> map = new LinkedHashMap<>();
    //    map.put("Methods","SmsSend");
    //    map.put("CorpID","129703");
    //    map.put("LoginName","Admin");
    //    //map.put("Password","298041");
    //    map.put("SecretKey",SecretKey);
    //    map.put("TimeStamp",timeStamp);
    //    map.put("PhoneNumbers","18327599237");
    //    map.put("LongSms","1");
    //    map.put("Content","***您好，我们已为您开通同济咨询企业邮箱。登录地址：www.tongji-ec.com.cn，首页右下角点击【企业邮局】，您的用户名：****，初始密码：Tjec33626700，完整邮箱地址为：****@tongji-ec.com.cn。首次登录请立即修改您的密码。如需帮助，请咨询021-33626713，黄伟之/刘华。  系统短信，请勿直接回复。");
    //    String s = sendGet2("http://sms.mobset.com:8095/SDK3/Sms", map);
    //    //String s = sendGet2("http://sms.mobset.com:8080/Api", map);
    //    System.out.println(s);
    //}
}


